import { ref } from 'vue';
import { accountService } from '@/services/security/LoginAccount';
import { ELForm, FormItemValidate, FormRules } from '@/utils/types';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Ref } from '@vue/reactivity';

export interface UseUpgradePassword {
  oldPassword: Ref<string | null>;
  newPassword: Ref<string | null>;
  confirmPassword: Ref<string | null>;
  visible: Ref<boolean>;
  formRules: FormRules;
  handleClosePassword: () => void;
  confirmCancelPassword: (done: () => void) => void;
  handleUpdatePassword: () => Promise<void>;
}

export const useUpgradePassword = (passwordFormRef: Ref<ELForm | null>): UseUpgradePassword => {
  const oldPassword = ref(null as string | null);
  const newPassword = ref(null as string | null);
  const confirmPassword = ref(null as string | null);
  const visible = ref(false);

  const validatePassword: FormItemValidate = (rule, value, callback) => {
    if (value.length < 6) {
      callback(new Error('The password can not be less than 6 digits'));
    } else {
      callback();
    }
  };
  const validateConfirm: FormItemValidate = (rule, value, callback) => {
    if (value !== newPassword.value) {
      callback(new Error('两次输入密码不一致!'));
    } else {
      callback();
    }
  };

  const formRules: FormRules = {
    password: [{ required: true, trigger: 'blur', validator: validatePassword }],
    confirm: [{ required: true, trigger: 'blur', validator: validateConfirm }],
  };

  const handleClosePassword = () => {
    oldPassword.value = null;
    newPassword.value = null;
    confirmPassword.value = null;
    visible.value = false;
  };

  const confirmCancelPassword = (done: () => void) => {
    ElMessageBox.confirm('确认关闭？')
      .then(() => {
        oldPassword.value = null;
        newPassword.value = null;
        confirmPassword.value = null;
        done();
      })
      .catch(() => {});
  };

  const handleUpdatePassword = async () => {
    await passwordFormRef.value?.validate(valid => {
      if (valid) {
        accountService
          .upgradePassword(oldPassword.value as string, newPassword.value as string)
          .catch(e => {
            ElMessage.error((e as Error).message);
          })
          .finally(() => {
            handleClosePassword();
          });
      }
    });
  };

  return {
    oldPassword,
    newPassword,
    confirmPassword,
    visible,
    formRules,
    handleClosePassword,
    confirmCancelPassword,
    handleUpdatePassword,
  };
};
